import baseInfo from '@/utils/config'

export const Socket = {}
let Path = '' // 地址

/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = (path, eventName, cb) => {
  const { SCOKET_HOST } = baseInfo
  if (typeof WebSocket === 'undefined') {
    console.log('您的浏览器不支持webScoket')
  }

  if (!(path && eventName)) return
  Path = path
  const url = `${SCOKET_HOST}/web_socket/${path}`
  Socket[path] && Socket[path].close()
  if (!Socket[path]) {
    console.log('建立websocket连接')
    Socket[path] = new WebSocket(url)

    Socket[path].onopen = onopenWS

    Socket[path].pathName = path
    Socket[path].eventName = eventName

    Socket[path].onmessage = e => {
      if (e) {
        cb(e.data, path)
      }
    }

    Socket[path].onclose = oncloseWS
    return {
      chatSign: path,
      socket: Socket[path]
    }
  } else {
    console.log('websocket已连接')
  }
}

/**
 * 打开WS之后发送心跳
 */
const onopenWS = (event) => {
  const path = event.currentTarget.pathName
  if (Socket[path].readyState === 1) {
    Socket[path].send('ping')
  }
}

/**
 * 发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = (path, ping = 'ping', time = 5000) => {
  if (Socket[path].setIntervalWesocketPush) {
    clearInterval(Socket[path].setIntervalWesocketPush)
  }

  Socket[path].send(ping)
  Socket[path].setIntervalWesocketPush = setInterval(() => {
    Socket[path].send(ping)
  }, time)
}

/**
 * 断开重连
 */
const oncloseWS = (event) => {
  if (event.code === 1000) return
  const path = event.currentTarget.pathName
  const eventName = event.currentTarget.eventName
  if (Socket[path].readyState !== 1) {
    if (Socket[path].setIntervalWesocketPush) {
      clearInterval(Socket[path].setIntervalWesocketPush)
    }

    console.log('websocket已断开....正在尝试重连')

    Socket[path] = null

    setTimeout(function () {
      Reconnection(path, eventName)
    }, 60000)
  }
}

/**
 * 重连函数
 * @constructor
 */
const Reconnection = (path, eventName) => {
  createSocket(path, eventName)
}
